package com.codedef.cidaren.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codedef.cidaren.common.exception.CustomException;
import com.codedef.cidaren.common.response.ResultCode;
import com.codedef.cidaren.constants.BaseConstant;
import com.codedef.cidaren.dao.UserDao;
import com.codedef.cidaren.entity.UserEntity;
import com.codedef.cidaren.service.UserService;
import com.codedef.cidaren.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    /**
     * 通过用户名密码验证用户是否登录成功，成功返回UserEntity对象，失败返回null
     * username字段可以为 用户名、手机号、电子邮箱
     * @param username
     * @param password
     * @return
     */
    public UserEntity userLoginCheck(String username, String password) {
        List<UserEntity> dbUsers = getByUsernameOrEmailOrTel(username);

        for (UserEntity u : dbUsers) {
            // 对Password加盐加密
            password = DigestUtils.md5Hex(BaseConstant.SaltFront + password + u.getSalt());
            // 将新生成的password与数据库中的比较
            if (password.equals(u.getPassword())) {
                return u;
            }
        }
        return null;
    }

    /**
     * 执行用户注册逻辑
     * @param user
     * @return
     */
    public boolean userRegister(UserEntity user) {
        // 检查用户名是否存在
        if (userDao.selectCount(new QueryWrapper<UserEntity>().eq("username", user.getUsername())) != 0) {
            // 用户名已存在
            throw new CustomException(ResultCode.USER_HAS_EXISTED);
        }

        // 检查邮箱是否存在
        if (userDao.selectCount(new QueryWrapper<UserEntity>().eq("email", user.getEmail())) != 0) {
            // 用户名已存在
            throw new CustomException(ResultCode.USER_EMAIL_HAS_EXISTED);
        }

        // 生成用户的盐
        String salt = RandomUtil.getRandomSalt();
        user.setSalt(salt);
        // Md5密码
        user.setPassword(DigestUtils.md5Hex(BaseConstant.SaltFront + user.getPassword() + salt));
        // 其他
        user.setLevel(1);
        user.setTax(0);
        user.setStatus(0);

        // 存入数据库
        if (userDao.insert(user) != 1) {
            throw new CustomException(ResultCode.FAIL);
        }

        return true;
    }


    /* ------------------------- 内部方法 ------------------------- */

    private List<UserEntity> getByUsernameOrEmailOrTel(String value) {
        List<UserEntity> userEntities = userDao.selectList(
                new QueryWrapper<UserEntity>()
                        .eq("username", value).or().eq("email", value).or().eq("tel", value)
        );
        return userEntities;
    }



}
